package cn.miju.wechatpay.handler;

import cn.miju.wechatpay.constant.WechatpayConstant;
import cn.miju.wechatpay.content.CodeMessage;
import cn.miju.wechatpay.request.WechatpayQueryOrderReq;
import cn.miju.wechatpay.response.WechatpayQueryOrderResp;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * <pre>
 * 业务类
 * </pre>
 *
 * @author Huzb
 * @version 1.0.0
 * @since 2023年05月04日 16:40
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatpayQueryOrderHandler extends AbstractWechatpayHandler<WechatpayQueryOrderReq, WechatpayQueryOrderResp> {


    /**
     * 请求参数前置处理
     *
     * @param req 请求参数
     * @return 结果
     */
    @Override
    protected String beforeRequest(WechatpayQueryOrderReq req) {
        return null;
    }

    /**
     * 核心执行
     *
     * @param req 请求参数
     * @return 结果
     */
    @Override
    public WechatpayQueryOrderResp doPlan(WechatpayQueryOrderReq req) {
        if (!StringUtils.hasLength(req.getOutTradeNo()) && !StringUtils.hasLength(req.getTransactionId())) {
            return WechatpayQueryOrderResp.builder()
                    .code(CodeMessage.FAIL.getCode())
                    .msg(CodeMessage.FAIL.getMsg() + "微信支付订单号和商户订单号不可同时为空").build();
        }
        CloseableHttpClient httpClient = super.getWechatpayClient(req.getWechatpayProperties());
        HttpGet httpGet;
        if (StringUtils.hasLength(req.getTransactionId())) {
            // 微信支付订单号查询
            httpGet = super.getHttpGet(req.getWechatpayProperties().getUrl()
                    + WechatpayConstant.ApiUri.QUERY_ORDER_BY_TRANSACTIONS_ID
                    + req.getTransactionId()
                    + "?mchid="
                    + req.getWechatpayProperties().getMchId());
        } else {
            // 商户订单号查询
            httpGet = super.getHttpGet(req.getWechatpayProperties().getUrl()
                    + WechatpayConstant.ApiUri.QUERY_ORDER_BY_OUT_TRADE_NO
                    + req.getOutTradeNo()
                    + "?mchid="
                    + req.getWechatpayProperties().getMchId());
        }

        CloseableHttpResponse response = null;
        WechatpayQueryOrderResp resp = null;

        // 发起请求
        try {
            try {
                log.info("API--查询订单--【/v3/pay/transactions/(查询订单)】-->RequestURI：{}", httpGet.getURI());
                response = httpClient.execute(httpGet);
                String resultStr = EntityUtils.toString(response.getEntity());
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("API--查询订单--【/v3/pay/transactions/(查询订单)】-->httpCode:{} Response：{}", statusCode, resultStr);
                resp = this.afterResponse(resultStr, statusCode);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } catch (IOException e) {
            log.error("API--查询订单--【/v3/pay/transactions/(查询订单)】-->Exception：{}", e.getMessage(), e);
            return WechatpayQueryOrderResp.builder()
                    .code(CodeMessage.FAIL.getCode())
                    .msg(CodeMessage.FAIL.getMsg() + e.getMessage()).build();
        }
        return resp;
    }

    /**
     * 响应参数后置处理
     *
     * @param result     响应报文
     * @param statusCode 响应状态码
     * @return 结果
     */
    @Override
    protected WechatpayQueryOrderResp afterResponse(String result, int statusCode) {
        if (statusCode == 200) {
            WechatpayQueryOrderResp resp = JSON.parseObject(result, WechatpayQueryOrderResp.class);
            resp.setCode(CodeMessage.SUCCESS.getCode());
            resp.setMsg(CodeMessage.SUCCESS.getMsg());
            return resp;
        }else {
            JSONObject jsonObject = JSON.parseObject(result);
            return WechatpayQueryOrderResp.builder()
                    .code(CodeMessage.FAIL.getCode())
                    .msg(CodeMessage.FAIL.getMsg() + "【" + jsonObject.get("code") + "】" + jsonObject.get("message"))
                    .build();
        }
    }
}
